package com.woniuxy.flowable.task;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送申请失败消息处理器
 * 在流程被拒绝时调用，将订单状态更新为已拒绝
 */
@Slf4j
@Component
public class SendFailureMessageHandler implements JavaDelegate {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Override
    public void execute(DelegateExecution execution) {
        try {
            // 获取流程变量
            String businessKey = execution.getProcessInstanceBusinessKey();
            String rejectReason = (String) execution.getVariable("rejectReason");
            String outcome = (String) execution.getVariable("outcome");
            
            log.info("发送申请失败消息，业务键：{}，拒绝原因：{}，结果：{}", businessKey, rejectReason, outcome);
            
            if (businessKey != null) {
                // 调用订单服务更新订单状态
                String orderServiceUrl = "http://localhost:8007/api/orders/" + businessKey + "/approve-reject";
                
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("orderId", businessKey);
                requestBody.put("orderNo", execution.getVariable("orderNo"));
                requestBody.put("rejectReason", rejectReason);
                requestBody.put("status", "REJECTED");
                
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                
                restTemplate.postForObject(orderServiceUrl, request, String.class);
                
                log.info("订单状态更新成功，订单ID：{}，拒绝原因：{}", businessKey, rejectReason);
            } else {
                log.warn("业务键为空，无法更新订单状态");
            }
            
        } catch (Exception e) {
            log.error("发送申请失败消息失败", e);
            throw new RuntimeException("发送申请失败消息失败: " + e.getMessage());
        }
    }
}


